<template>
  <view class="container-manage-modal" v-if="visible">
    <view class="modal-overlay" @tap="closeModal">
      <view class="modal-container" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">容器管理</text>
          <text class="modal-close" @click="closeModal">✕</text>
        </view>
        
        <view class="modal-content">
          <!-- 加载状态 -->
          <view class="loading-container" v-if="loading">
            <text class="loading-text">加载中...</text>
          </view>
          
          <!-- 空状态 -->
          <view class="empty-container" v-else-if="containerList.length === 0">
            <text class="empty-text">暂无容器数据</text>
          </view>
          
          <!-- 容器卡片列表 -->
          <scroll-view v-else scroll-y class="container-scroll">
            <view class="container-list">
              <view class="container-card" v-for="container in containerList" :key="container.rowid">
                <view class="card-header">
                  <text class="container-code">{{ container['686b42983f0e1b398c1cac71'] || '未知容器' }}</text>
                  <text class="container-status" :class="getStatusClass(container['6889ccc302274fada36ece1c'])">
                    {{ container['6889ccc302274fada36ece1c'] || '未知状态' }}
                  </text>
                </view>
                <view class="card-content">
                  <view class="info-item">
                    <text class="info-label">配送站点:</text>
                    <text class="info-value">{{ getDestinationName(container) || '-' }}</text>
                  </view>
                  <view class="info-item">
                    <text class="info-label">容器类型:</text>
                    <text class="info-value">{{ container['686b42ef3f0e1b398c1cac85'] || '-' }}</text>
                  </view>
                  <view class="info-item">
                    <text class="info-label">存放商品数:</text>
                    <text class="info-value">{{ container['68b0227e6b50e0d4f7a775bc'] || '0' }} 个</text>
                  </view>
                  <view class="info-item">
                    <text class="info-label">体积:</text>
                    <text class="info-value">{{ container['68ad72988252ec8de889119c'] || '0' }} m³</text>
                  </view>
                  <view class="info-item">
                    <text class="info-label">重量:</text>
                    <text class="info-value">{{ container['68ad72aa8252ec8de88911a5'] || '0' }} kg</text>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import http from '../utils/request'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['update:visible', 'close'])

// 响应式数据
const loading = ref(false)
const containerList = ref([])

// 关闭弹框
const closeModal = () => {
  emit('update:visible', false)
  emit('close')
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    '使用中': 'status-active',
    '空闲': 'status-idle',
    '维修中': 'status-maintenance'
  }
  return statusMap[status] || 'status-default'
}

// 获取配送站点名称
const getDestinationName = (container) => {
  // 从配送站点关联字段获取名称
  // 688864d80e18077cf8de3cb9 是配送站点的关联字段ID
  const destinationInfo = container['68a80b0d0372283d1e925105']
  if (destinationInfo && typeof destinationInfo === 'object') {
    return destinationInfo.name || destinationInfo.displayName || '-'
  }
  return '-'
}

// 获取所有容器数据（只保留状态为使用中的过滤器）
const getAllContainers = async () => {
  loading.value = true
  
  const allData = []
  const seenIds = new Set() // 用于去重
  let currentPage = 1
  let totalRecords = 0
  
  try {
    while (true) {
      const res = await http.post('https://www.dachen.vip/api/workflow/hooks2/NjhjZDE2ZDZhYmFlZTk0OGVjYjU1OGNj', {
        worksheetId: 'rqgl',
        userRowid: "2679ec1d-7e61-476c-ab9f-c2349fc778ca",
        code: "001",
        pageSize: 100,
        pageNum: currentPage,
        filters: [
          {
            "controlId": "6889ccc302274fada36ece1c",
            "dataType": 11,
            "spliceType": 1,
            "filterType": 2,
            "values": ["使用中"]
          }
        ]
      })
      
      console.log(`第${currentPage}页容器请求参数:`, {
        worksheetId: 'rqgl',
        userRowid: "2679ec1d-7e61-476c-ab9f-c2349fc778ca",
        code: "001",
        pageSize: 100,
        pageNum: currentPage,
        filters: [{
          "controlId": "6889ccc302274fada36ece1c",
          "dataType": 11,
          "spliceType": 1,
          "filterType": 2,
          "values": ["使用中"]
        }]
      })
      
      console.log(`第${currentPage}页容器API响应:`, res)
      
      if (res && res.success === "true") {
        // 解析data字段中的JSON字符串
        let responseData;
        try {
          responseData = JSON.parse(res.data);
          console.log(`第${currentPage}页容器解析后的数据:`, responseData)
        } catch (e) {
          console.error('解析容器数据失败:', e);
          console.error('原始容器数据:', res.data);
          break;
        }
        
        // 记录总数据量
        if (currentPage === 1) {
          totalRecords = responseData.total || 0;
          console.log('容器总记录数:', totalRecords)
        }
        
        if (responseData.rows && responseData.rows.length > 0) {
          console.log(`第${currentPage}页获取到${responseData.rows.length}条容器数据`)
          
          // 去重处理：只添加未见过的数据
          responseData.rows.forEach(item => {
            const itemId = item.rowid || item.id || JSON.stringify(item)
            if (!seenIds.has(itemId)) {
              seenIds.add(itemId)
              allData.push(item)
            }
          })
          
          // 检查是否还有更多数据
          const hasNextPage = responseData.total > (currentPage * 100)
          
          if (!hasNextPage) {
            console.log('没有更多容器数据，结束分页')
            break
          }
          
          currentPage++
        } else {
          console.log('当前页没有容器数据，结束分页')
          break
        }
      } else {
        console.error('获取容器数据失败:', res);
        break
      }
    }
    
    containerList.value = allData
    
    console.log('获取所有容器数据', {
      originalCount: allData.length,
      total: totalRecords
    });
    
  } catch (error) {
    console.error('获取容器数据过程中发生错误:', error);
    
    // 特殊处理JSON解析错误
    if (error.message && error.message.includes('Unexpected token')) {
      uni.showToast({
        title: '容器数据格式错误',
        icon: 'error',
        duration: 2000
      })
    } else {
      uni.showToast({
        title: '获取容器数据失败',
        icon: 'error',
        duration: 2000
      })
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getAllContainers()
})
</script>

<style lang="scss" scoped>
.container-manage-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  
  .modal-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .modal-container {
    background-color: #fff;
    border-radius: 12px;
    width: 90%;
    max-width: 600px;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #e5e5e5;
    
    .modal-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
    
    .modal-close {
      font-size: 20px;
      color: #999;
      cursor: pointer;
      padding: 4px;
      
      &:hover {
        color: #666;
      }
    }
  }
  
  .modal-content {
    flex: 1;
    padding: 0;
    overflow: hidden;
  }
  
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px;
    
    .loading-text {
      font-size: 14px;
      color: #666;
    }
  }
  
  .empty-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px;
    
    .empty-text {
      font-size: 14px;
      color: #999;
    }
  }
  
  .container-scroll {
    height: 100%;
    max-height: 60vh;
  }
  
  .container-list {
    padding: 16px;
  }
  
  .container-card {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border: 1px solid #f0f0f0;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      
      .container-code {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }
      
      .container-status {
        font-size: 12px;
        padding: 4px 8px;
        border-radius: 4px;
        font-weight: 500;
        
        &.status-active {
          background-color: #e6f7ff;
          color: #1890ff;
        }
        
        &.status-idle {
          background-color: #f6ffed;
          color: #52c41a;
        }
        
        &.status-maintenance {
          background-color: #fff7e6;
          color: #fa8c16;
        }
        
        &.status-default {
          background-color: #f5f5f5;
          color: #999;
        }
      }
    }
    
    .card-content {
      .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-label {
          font-size: 13px;
          color: #666;
          flex-shrink: 0;
          margin-right: 8px;
        }
        
        .info-value {
          font-size: 13px;
          color: #333;
          text-align: right;
          flex: 1;
        }
      }
    }
  }
}
</style>